package cloudPayAdmin.admin.service.hicatcard.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import cloudPayAdmin.admin.dbapp.entity.hicatcard.card.TCard;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.card.TCardService;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUser;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserCard;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserCardRecharge;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserCardService;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserCardTransfer;
import cloudPayAdmin.admin.dbapp.repo.hicatcard.card.CardRepo;
import cloudPayAdmin.admin.dbapp.repo.hicatcard.card.CardServiceRepo;
import cloudPayAdmin.admin.dbapp.repo.hicatcard.user.UserCardRechargeRepo;
import cloudPayAdmin.admin.dbapp.repo.hicatcard.user.UserCardRepo;
import cloudPayAdmin.admin.dbapp.repo.hicatcard.user.UserCardServiceRepo;
import cloudPayAdmin.admin.dbapp.repo.hicatcard.user.UserCardTransferRepo;
import cloudPayAdmin.admin.dbapp.repo.hicatcard.user.UserRepo;
import cloudPayAdmin.util.IdGenerator;
import cloudPayAdmin.util.TimeUtil;

@Component
@Transactional
public class UserCardService {
	
	@Autowired
	UserCardRepo userCardRepo;
	
	@Autowired
	UserCardTransferRepo userCardTransferRepo;
	
	@Autowired
	UserRepo userRepo;
	
	@Autowired
	CardServiceRepo cardServiceRepo;
	
	@Autowired
	UserCardServiceRepo userCardServiceRepo;
	
	@Autowired
	UserCardRechargeRepo userCardRechargeRepo;
	
	@Autowired
	CardRepo cardRepo;
	
	@Transactional(readOnly=true)
	public TUserCardRecharge findUserRechargeById(Long userRechargeId) {
		return userCardRechargeRepo.findOne(userRechargeId);
	}
	
	@Transactional(readOnly=true)
	public TUser findTransferTargetUser(Long userCardId) {
		List<TUserCardTransfer> userCardTransfer = userCardTransferRepo.findBySourceUserCardId(userCardId);
		if(CollectionUtils.isEmpty(userCardTransfer)) {
			return null;
		}
		return userRepo.findOne(userCardTransfer.get(0).getTargetUserId());
	}
	
	
	@Transactional(readOnly=true)
	public TUserCard findById(Long userCardId) {
		return userCardRepo.findOne(userCardId);
	}
	
	@Transactional(readOnly=true)
	public TUserCard findByUserCardNumber(String userCardNumber) {
		return userCardRepo.findByUserCardNumber(userCardNumber);
	}
	
	@Transactional(readOnly=true)
	public List<TUserCard> findByUserCardRechargeId(Long userCardRechargeId) {
		return userCardRepo.findByUserCardRechargeId(userCardRechargeId);
	}
	
	public List<TUserCard> save(List<TUserCard> userCardList) {
		return userCardRepo.save(userCardList);
	}
	
	/**
	 * 公司赠送卡片方法
	 * @param phone
	 * @param presentCount
	 * @param cardId
	 * @return
	 */
	public void companyPresentCard(Long[] userIds , Map<String,Object> presentItemMap,String remark) {
		TUserCardRecharge userCardRecharge = new TUserCardRecharge();
		userCardRecharge.setRechargeUserCount(userIds.length);
		userCardRecharge.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
		userCardRecharge.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
		
		StringBuilder rechargeContent = new StringBuilder();
		
		for (Map.Entry<String, Object> entry : presentItemMap.entrySet()) {  
			
			if(StringUtils.isNotEmpty(String.valueOf(entry.getValue()))) {
				TCard card = cardRepo.findOne(Long.parseLong(entry.getKey()));
				String cardName = card.getCardName();
				rechargeContent.append(cardName).append((String.valueOf(entry.getValue()))).append("张,");
			}	
		}  
		
		userCardRecharge.setRechargeContent(rechargeContent.substring(0, rechargeContent.length() - 1));
		userCardRecharge.setRemark(remark);
		userCardRecharge = userCardRechargeRepo.save(userCardRecharge);
		
		List<TUserCard> userCardList = new ArrayList<TUserCard>();
		List<TUserCardService> userCardServiceList = new ArrayList<TUserCardService>();
		for(Long userId : userIds) {
		//	TUser user = userRepo.findOne(userId);
			for (Map.Entry<String, Object> entry : presentItemMap.entrySet()) {  
				
				if(StringUtils.isNotEmpty(String.valueOf(entry.getValue()))) {
					Long cardId = Long.parseLong(entry.getKey());
					TCard card = cardRepo.findOne(cardId);
					Integer count = Integer.parseInt(String.valueOf(entry.getValue()));
					
					for(int i=0;i<count;i++) {
						TUserCard userCard = new TUserCard();
						userCard.setUserId(userId);
						userCard.setCardId(cardId);
						userCard.setUserCardNumber(IdGenerator.generateOrderId(IdGenerator.ORDERID_PREFIX_USER_CARD, "00", "0000"));
						userCard.setSource(TUserCard.SOURCE_COMPANY_PRESENT);
						userCard.setSourceUserId(null);
						userCard.setStatus(TUserCard.STATUS_ACTIVE);
						userCard.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
						userCard.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
						userCard.setUserCardRechargeId(userCardRecharge.getUserCardRechargeId());
						Integer effectiveDay = card.getEffectiveDay();
						String endTime = TimeUtil.getFormatTime(TimeUtil.addDateNDay(new Date(),effectiveDay), TimeUtil.DATE_PATTERN_NOSEPARTOR);
						endTime = StringUtils.substring(endTime, 0, endTime.length() - 6) + "235959";						
						userCard.setEndTime(endTime);
						userCardList.add(userCard);
					}
				}			
			}  
		}
		
		userCardList = userCardRepo.save(userCardList);
		
		for(TUserCard userCard : userCardList) {
			List<TCardService> cardServiceList = cardServiceRepo.findByCardId(userCard.getCardId());
			for(TCardService cardService : cardServiceList) {
				TUserCardService userCardService = new TUserCardService();
				userCardService.setUserCardId(userCard.getUserCardId());
				userCardService.setServiceId(cardService.getServiceId());
				userCardService.setServiceTime(cardService.getServiceTime());
				userCardService.setStatus("1");
				userCardService.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
				userCardService.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
				userCardService.setEnable(true);
				userCardServiceList.add(userCardService);
			}	
			
		}
		
		userCardServiceRepo.save(userCardServiceList);
	}
	
	/**
	 * 公司赠送卡片方法
	 * @param phone
	 * @param presentCount
	 * @param cardId
	 * @return
	 */
	public void companyPresentCard(String phone,Integer presentCount,Long cardId) {
		
		List<TUserCard> userCardList = new ArrayList<TUserCard>();
		List<TUserCardService> userCardServiceList = new ArrayList<TUserCardService>();
		
		List<TUser> userList = userRepo.findByPhone(phone);
		if(!CollectionUtils.isEmpty(userList)) {
			TUser user  = userList.get(0);
			for(int i=0;i<presentCount;i++) {
				TUserCard userCard = new TUserCard();
				userCard.setUserId(user.getUserId());
				userCard.setCardId(cardId);
				userCard.setUserCardNumber(IdGenerator.generateOrderId(IdGenerator.ORDERID_PREFIX_USER_CARD, "00", "0000"));
				userCard.setSource(TUserCard.SOURCE_COMPANY_PRESENT);
				userCard.setSourceUserId(null);
				userCard.setStatus(TUserCard.STATUS_NOT_ACTIVE);
				userCard.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
				userCard.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
				userCardList.add(userCard);			
			}
			
			userCardList = userCardRepo.save(userCardList);
			
			for(TUserCard userCard : userCardList) {
				List<TCardService> cardServiceList = cardServiceRepo.findByCardId(userCard.getCardId());
				for(TCardService cardService : cardServiceList) {
					TUserCardService userCardService = new TUserCardService();
					userCardService.setUserCardId(userCard.getUserCardId());
					userCardService.setServiceId(cardService.getServiceId());
					userCardService.setServiceTime(cardService.getServiceTime());
					userCardService.setStatus("1");
					userCardService.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
					userCardService.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
					userCardService.setEnable(true);
					userCardServiceList.add(userCardService);
				}			
			}
			
			userCardServiceRepo.save(userCardServiceList);
		
		}
	}
	
	public void saveUserCardListAndUserCardServiceList(List<TUserCard> userCardList,List<TUserCardService> userCardServiceList) {
		if(CollectionUtils.isNotEmpty(userCardList)) {
			userCardRepo.save(userCardList);
		}
		
		if(CollectionUtils.isNotEmpty(userCardServiceList)) {
			userCardServiceRepo.save(userCardServiceList);
		}
	}
}
